import {defineStore} from "pinia";
import request from '@/api/login.ts'
import {getToken, removeToken, setToken} from "../../utils/tokenUtils.ts";
const UserStore = defineStore('user', {
  state: () => {
    return {
        token: getToken(),
        userInfo: {}
    }
  },
  actions: {
    login(userInfo:any){
        return new Promise((resolve, reject) => {
            request.login(userInfo).then((res:any) => {
                setToken(res.data.token)
                this.token = res.data.token
                resolve(res)
            }).catch((error:any) => {
                reject(error)
            })
        })
    },
      // 获取用户信息
      getInfo() {
          return new Promise((resolve, reject) => {
              request.getInfo().then((res:any) => {
                  this.userInfo = res.data.user
                  resolve(res)
              }).catch((error:any) => {
                  reject(error)
              })
          })
      },
      // 退出系统
      logOut() {
          return new Promise((resolve, reject) => {
              request.logout(this.token).then(() => {
                  this.token = ''
                  removeToken()
                  resolve()
              }).catch(error => {
                  reject(error)
              })
          })
      }
  }
})
export default UserStore
